﻿using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mate.Framework.Extensions
{
    public static class HtmlControlExtensions
    {
        #region TextFor 文本框
        /// <summary>
        /// TextFor
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="title">标题</param>
        /// <param name="id">控件id</param>
        /// <param name="name">控件name(为空时，name=id)</param>
        /// <param name="classStr">class名称（默认有form-control，多个用空格隔开）</param>
        /// <param name="htmlAttributes">控件属性(格式:key='value')，多个用空格隔开</param>
        /// <param name="required">是否可空</param>
        /// <param name="titleWidth">title宽度(默认3)</param>
        /// <param name="inputWidth">文本框宽度(默认4)</param>
        /// <param name="value">默认值</param>
        /// <param name="isReadonly">文本框是否只读，true添加readonly='readonly'属性</param>
        /// <param name="helpText">输入提示信息</param>
        /// <returns></returns>
        public static IHtmlContent TextFor(this IHtmlHelper htmlHelper, string title, string id, string name = "", string classStr = "",
            string htmlAttributes = null, bool required = true, int titleWidth = 3, int inputWidth = 4, string value = "", bool isReadonly = false,
            string helpText = "")
        {
            StringBuilder html = new StringBuilder();

            if (string.IsNullOrWhiteSpace(name)) name = id;
            if (isReadonly == true) htmlAttributes += " readonly=\"readonly\"";

            html.Append("<div class=\"form-group\">\n");
            html.Append($"   <label class=\"control-label col-xs-{titleWidth}\">{title}\n");
            if (required == true)
            {
                html.Append("       <span class=\"required\">*</span>\n");
            }
            html.Append("   </label>\n");
            html.Append($"   <div class=\"col-xs-{inputWidth}\">\n");
            html.Append($"      <input id=\"{id}\" name=\"{name}\" class=\"form-control {classStr}\" type=\"text\" value=\"{value}\" {htmlAttributes} />\n");
            if (!string.IsNullOrWhiteSpace(helpText))
            {
                html.Append($"      <span class=\"help-block\">" + helpText + "</span>\n");
            }
            html.Append("   </div>\n");
            html.Append("</div>\n");
            return new HtmlString(html.ToString());
        }
        #endregion

        #region TextTextFor 文本框(标题也是文本框)
        /// <summary>
        /// TextFor
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="id">控件id</param>
        /// <param name="name">控件name(为空时，name=id)</param>
        /// <param name="titleId">标题控件id</param>
        /// <param name="titleName">标题控件name</param>
        /// <param name="classStr">class名称（默认有form-control，多个用空格隔开）</param>
        /// <param name="htmlAttributes">控件属性(格式:key='value')，多个用空格隔开</param>
        /// <param name="required">是否可空</param>
        /// <param name="titleWidth">title宽度(默认3)</param>
        /// <param name="inputWidth">文本框宽度(默认4)</param>
        /// <param name="value">默认值</param>
        /// <param name="titleValue">标题默认值</param>
        /// <param name="isReadonly">文本框是否只读，true添加readonly='readonly'属性</param>
        /// <returns></returns>
        public static IHtmlContent TextTextFor(this IHtmlHelper htmlHelper, string id, string titleId, string name = "", string titleName = "", string classStr = "",
            string htmlAttributes = null, int titleWidth = 3, int inputWidth = 4, string value = "", string titleValue = "", bool isReadonly = false)
        {
            StringBuilder html = new StringBuilder();

            if (string.IsNullOrWhiteSpace(name)) name = id;
            if (string.IsNullOrWhiteSpace(titleName)) titleName = titleId;
            if (isReadonly == true) htmlAttributes += " readonly=\"readonly\"";

            html.Append("<div class=\"form-group\">\n");
            html.Append($"   <div class=\"col-xs-{titleWidth}\">\n");
            html.Append($"      <input id=\"{titleId}\" name=\"{titleName}\" class=\"form-control\" type=\"text\" value=\"{titleValue}\"/>\n");
            //if (required == true)
            //{
            //    //html.Append("       <span class=\"required\">*</span>\n");
            //}
            html.Append("   </div>\n");
            html.Append($"   <div class=\"col-xs-{inputWidth}\">\n");
            html.Append($"      <input id=\"{id}\" name=\"{name}\" class=\"form-control {classStr}\" type=\"text\" value=\"{value}\" {htmlAttributes} />\n");
            html.Append("   </div>\n");
            html.Append("</div>\n");
            return new HtmlString(html.ToString());
        }
        #endregion

        #region SelectFor 下拉框
        /// <summary>
        /// 性别 SelectFor
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="title">标题</param>
        /// <param name="id">控件id</param>
        /// <param name="name">控件name(为空时，name=id)</param>
        /// <param name="isSelect">是否有请选择项</param>
        /// <param name="isSelectValue">请选择项值</param>
        /// <param name="optionValue">当前选择项值</param>
        /// <param name="classStr">class名称（默认有form-control，多个用空格隔开）</param>
        /// <param name="htmlAttributes">控件属性(格式:key='value')，多个用空格隔开</param>
        /// <param name="required">是否可空</param>
        /// <param name="titleWidth">title宽度(默认3)</param>
        /// <param name="inputWidth">文本框宽度(默认4)</param>
        /// <returns></returns>
        public static IHtmlContent SexSelectFor(this IHtmlHelper htmlHelper, string title, string id, string name = ""
            , bool isSelect = true, string isSelectValue = "", string optionValue = "",
            string classStr = "", string htmlAttributes = null, bool required = true, int titleWidth = 3, int inputWidth = 4)
        {
            return htmlHelper.SelectFor(title, new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string, string>("1","男"),
                new KeyValuePair<string, string>("2","女")
            }, id, name, isSelect, isSelectValue, optionValue, classStr, htmlAttributes, required, titleWidth, inputWidth);
        }

        /// <summary>
        /// SelectFor
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="options">值</param>
        /// <param name="title">标题</param>
        /// <param name="id">控件id</param>
        /// <param name="name">控件name(为空时，name=id)</param>
        /// <param name="isSelect">是否有请选择项</param>
        /// <param name="isSelectValue">请选择项值</param>
        /// <param name="optionValue">当前选择项值</param>
        /// <param name="classStr">class名称（默认有form-control，多个用空格隔开）</param>
        /// <param name="htmlAttributes">控件属性(格式:key='value')，多个用空格隔开</param>
        /// <param name="required">是否可空</param>
        /// <param name="titleWidth">title宽度(默认3)</param>
        /// <param name="inputWidth">文本框宽度(默认4)</param>
        /// <returns></returns>
        public static IHtmlContent SelectFor(this IHtmlHelper htmlHelper, string title, IList<KeyValuePair<string, string>> options, string id, string name = ""
            , bool isSelect = false, string isSelectValue = "", string optionValue = "",
            string classStr = "", string htmlAttributes = null, bool required = true, int titleWidth = 3, int inputWidth = 4)
        {
            StringBuilder html = new StringBuilder();

            if (string.IsNullOrWhiteSpace(name)) name = id;

            html.Append("<div class=\"form-group\">\n");
            html.Append($"   <label class=\"control-label col-xs-{titleWidth}\">{title}\n");
            if (required == true)
            {
                html.Append("       <span class=\"required\">*</span>\n");
            }
            html.Append("   </label>\n");
            html.Append($"   <div class=\"col-xs-{inputWidth}\">\n");
            html.Append($"      <select id=\"{id}\" name=\"{name}\" class=\"form-control {classStr}\" {htmlAttributes} >\n");

            if (isSelect == true)
            {
                html.Append($"<option value=\"{isSelectValue}\">-请选择-</option>\n");
            }

            foreach (var item in options)
            {
                string selected = "";
                if (!string.IsNullOrWhiteSpace(optionValue) && item.Key == optionValue)
                {
                    selected = " selected=\"selected\"";
                }
                html.Append($"<option value=\"{item.Key}\"{selected}>{item.Value}</option>\n");
            }
            html.Append("       </select>\n");
            html.Append("   </div>\n");
            html.Append("</div>\n");
            return new HtmlString(html.ToString());
        }
        #endregion

        #region RadioFor 单选按钮
        /// <summary>
        /// RadioFor
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="title">标题</param>
        /// <param name="name">控件name（id=name+索引）</param>
        /// <param name="selectValue">当前选择项值</param>
        /// <param name="required">是否可空</param>
        /// <param name="titleWidth">title宽度(默认3)</param>
        /// <param name="inputWidth">文本框宽度(默认4)</param>
        /// <returns></returns>
        public static IHtmlContent EnableRadioFor(this IHtmlHelper htmlHelper, string title = "是否启用", string name = "is_enable", string selectValue = "True",
            bool required = true, int titleWidth = 3, int inputWidth = 4)
        {
            return htmlHelper.RadioFor(title, name, new List<KeyValuePair<string, string>>()
                                                {
                                                    new KeyValuePair<string, string>("True","是"),
                                                    new KeyValuePair<string, string>("False","否")
                                                }, selectValue, required, titleWidth, inputWidth);
        }
        /// <summary>
        /// RadioFor
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="title">标题</param>
        /// <param name="name">控件name（id=name+索引）</param>
        /// <param name="data">值</param>
        /// <param name="value">radio value的值</param>
        /// <param name="descdescribe">radio 的描述</param>
        /// <param name="selectValue">当前选择项值</param>
        /// <param name="required">是否可空</param>
        /// <param name="titleWidth">title宽度(默认3)</param>
        /// <param name="inputWidth">文本框宽度(默认4)</param>
        /// <returns></returns>
        public static IHtmlContent RadioFor(this IHtmlHelper htmlHelper, string title, string name, IList<KeyValuePair<string, string>> data, string selectValue = "",
            bool required = true, int titleWidth = 3, int inputWidth = 4)
        {
            StringBuilder html = new StringBuilder();

            html.Append("<div class=\"form-group\">\n");
            html.Append($"   <label class=\"control-label col-xs-{titleWidth}\">{title}\n");
            if (required == true)
            {
                html.Append("       <span class=\"required\">*</span>\n");
            }
            html.Append("   </label>\n");
            html.Append($"   <div class=\"col-xs-{inputWidth}\">\n");

            html.Append("       <div class=\"radio-list\">");
            int index = 1;
            foreach (var item in data)
            {
                html.Append("           <label class=\"radio-inline\">\n");
                string checkedStr = string.Empty;
                if (!string.IsNullOrWhiteSpace(selectValue) && item.Key == selectValue)
                {
                    checkedStr = " checked=\"checked\"";
                }
                html.Append($"<input{checkedStr} id=\"{name + index.ToString()}\" name=\"{name}\" type=\"radio\" value=\"{item.Key}\" /><span>{item.Value}</span>\n");
                html.Append("           </label>\n");
                index++;
            }
            html.Append("       </div>\n");
            html.Append("   </div>\n");
            html.Append("</div>\n");
            return new HtmlString(html.ToString());
        }
        #endregion

        #region UploadPictureFor 上传图片
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="title">标题</param>
        /// <param name="id">控件id</param>
        /// <param name="thumPicId">缩略图控件id</param>
        /// <param name="isThumPic">是否生成缩略图</param>
        /// <param name="picSrc">图片默认src</param>
        /// <param name="thumPicSrc">缩略图默认src</param>
        /// <param name="btnText">上传按钮文字</param>
        /// <param name="required">是否可空</param>
        /// <param name="titleWidth">title宽度(默认3)</param>
        /// <param name="inputWidth">文本框宽度(默认4)</param>
        /// <returns></returns>
        public static IHtmlContent UploadPictureFor(this IHtmlHelper htmlHelper, string title, string id, string thumPicId = "", bool isThumPic = false, string picSrc = "", string thumPicSrc = "",
           string btnText = "选 择 图 片", bool required = true, int titleWidth = 3, int inputWidth = 4)
        {
            StringBuilder html = new StringBuilder();
            html.Append("<div class=\"form-group\">\n");
            html.Append($"   <label class=\"control-label col-xs-{titleWidth}\">{title}\n");
            if (required == true)
            {
                html.Append("       <span class=\"required\">*</span>\n");
            }
            html.Append("   </label>\n");
            html.Append($"   <div class=\"col-xs-{inputWidth}\">\n");

            html.Append("       <div style=\"width:208px;\">\n");
            html.Append("           <div class=\"thumbnail\">\n");
            html.Append($"              <img src=\"{(isThumPic ? thumPicSrc : picSrc)}\" style=\"max-height:200px; max-width:200px;\" alt=\"\" id=\"img_{(isThumPic ? thumPicId : id)}\">\n");
            html.Append($"              <input id=\"{id}\" name=\"{id}\" type=\"hidden\" value=\"{picSrc}\" />\n");
            if (isThumPic == true)
            {
                html.Append($"          <input id=\"{thumPicId}\" name=\"{thumPicId}\" type=\"hidden\" value=\"{thumPicSrc}\" />\n");
            }
            html.Append("           <div class=\"caption\" style=\"text-align:center;\">\n");
            html.Append("               <span class=\"btn green fileinput-button\">\n");
            html.Append($"                  <span>{btnText}</span>\n");
            html.Append($"                  <input type=\"file\" id=\"fileupload_{id}\" name=\"pictureFile\" multiple=\"\" accept=\".jpg,.jpeg,.gif,.png\">\n");
            html.Append("               </span>\n");
            html.Append("           </div>\n");
            html.Append("       </div>\n");
            html.Append("   </div>\n");
            html.Append("</div>\n</div>\n");
            return new HtmlString(html.ToString());
        }

        #region UploadPictureJs
        /// <summary>
        /// 上传图片js
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="id">控件id</param>
        /// <param name="thumPicId">缩略图控件id</param>
        /// <param name="isThumPic">是否生成缩略图</param>
        /// <returns></returns>
        public static IHtmlContent UploadPictureJs(this IHtmlHelper htmlHelper, string id, string thumPicId = "", bool isThumPic = false)
        {
            StringBuilder html = new StringBuilder();
            html.Append("$('#fileupload_" + id + "').fileupload({");
            html.Append("   disableImageResize: false,\n");
            html.Append("   autoUpload: true,\n");
            html.Append($"   url: '/Upload/{(isThumPic ? "UpdateImage" : "UpdateImageNotZoom")}?imagePath={DateTime.Now.ToString("yyyyMMdd")}',\n");
            html.Append("   done: function (e, data) {\n");
            html.Append("       if (data.result.resultCode == 1000) {\n");
            if (isThumPic == true)
            {
                html.Append($"          $(\"#img_{thumPicId}\").attr(\"src\", data.result.data.thumImageUrl);\n");
            }
            else
            {
                html.Append($"          $(\"#img_{id}\").attr(\"src\", data.result.data.imageUrl);\n");
            }

            html.Append($"          $(\"#{id}\").val(data.result.data.imageUrl);\n");
            if (isThumPic == true)
            {
                html.Append($"          $(\"#{thumPicId}\").val(data.result.data.thumImageUrl);\n");
            }
            html.Append("       } else {\n");
            html.Append("           alert(data.result.message);\n");
            html.Append("   }\n");
            html.Append("}\n");
            html.Append("});");
            return new HtmlString(html.ToString());
        }
        #endregion
        #endregion

        #region CheckboxFor 复选框
        /// <summary>
        /// 复选框
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="title">标题</param>
        /// <param name="id">控件id</param>
        /// <param name="data">值</param>
        /// <param name="selectValue">当前选中的值</param>
        /// <param name="isInline">true横向展示，false纵向展示</param>
        /// <param name="required">是否可空</param>
        /// <param name="titleWidth">title宽度(默认3)</param>
        /// <param name="inputWidth">文本框宽度(默认4)</param>
        /// <returns></returns>
        public static IHtmlContent CheckboxFor(this IHtmlHelper htmlHelper, string title, string id, IList<KeyValuePair<string, string>> data, string[] selectValue = null
            , bool isInline = true, bool required = true, int titleWidth = 3, int inputWidth = 4)
        {
            StringBuilder html = new StringBuilder();
            html.Append("<div class=\"form-group\">\n");
            html.Append($"   <label class=\"control-label col-xs-{titleWidth}\">{title}\n");
            if (required == true)
            {
                html.Append("       <span class=\"required\">*</span>\n");
            }
            html.Append("   </label>\n");
            html.Append($"   <div class=\"col-xs-{inputWidth}\">\n");

            html.Append("       <div class=\"checkbox-list\">");
            int index = 1;
            string inlineClass = string.Empty;
            if (isInline)
            {
                inlineClass = "class=\"checkbox-inline\"";
            }
            foreach (var item in data)
            {
                string checkedStr = string.Empty;
                if (selectValue?.Contains(item.Key) == true)
                {
                    checkedStr = " checked=\"checked\"";
                }
                html.Append($"          <label{inlineClass}><input type = \"checkbox\" value=\"{item.Key}\" id=\"{id + index.ToString()}\" name=\"{id}\"{checkedStr}> {item.Value} </label> ");
                index++;
            }
            html.Append("       </div>\n");

            html.Append("   </div>\n");
            html.Append("</div>\n");
            return new HtmlString(html.ToString());
        }
        #endregion

        #region EditorFor 富文本框
        /// <summary>
        /// 富文本框
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="title">标题</param>
        /// <param name="id">控件id</param>
        /// <param name="required">是否可空</param>
        /// <param name="titleWidth">title宽度(默认3)</param>
        /// <param name="inputWidth">文本框宽度(默认4)</param>
        /// <param name="value">默认值</param>
        /// <returns></returns>
        public static IHtmlContent EditorFor(this IHtmlHelper htmlHelper, string title, string id,
           bool required = true, int titleWidth = 3, int inputWidth = 4, string value = "")
        {
            StringBuilder html = new StringBuilder();
            html.Append("<div class=\"form-group\">\n");
            html.Append($"   <label class=\"control-label col-xs-{titleWidth}\">{title}\n");
            if (required == true)
            {
                html.Append("       <span class=\"required\">*</span>\n");
            }
            html.Append("   </label>\n");
            html.Append($"   <div class=\"col-xs-{inputWidth}\">\n");
            html.Append($"      <script id=\"{id}\" name=\"{id}\" type=\"text/plain\" style=\"width:100%; height:300px;\">{value}</script>\n");
            html.Append("   </div>\n");
            html.Append("</div>\n");
            return new HtmlString(html.ToString());
        }
        #endregion

        #region UploadFileFor 上传文件
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="title">标题</param>
        /// <param name="id">控件id</param>
        /// <param name="required">是否可空</param>
        /// <param name="titleWidth">title宽度(默认3)</param>
        /// <param name="inputWidth">文本框宽度(默认4)</param>
        /// <param name="value">默认值</param>
        /// <returns></returns>
        public static IHtmlContent UploadFileFor(this IHtmlHelper htmlHelper, string title, string id, string btnText = "选择文件",
           bool required = true, int titleWidth = 3, int inputWidth = 4)
        {
            StringBuilder html = new StringBuilder();
            html.Append("<div class=\"form-group\">\n");
            html.Append($"   <label class=\"control-label col-xs-{titleWidth}\">{title}\n");
            if (required == true)
            {
                html.Append("       <span class=\"required\">*</span>\n");
            }
            html.Append("   </label>\n");
            html.Append($"   <div class=\"col-xs-{inputWidth}\">\n");
            html.Append($"      <input id=\"{id}\" name=\"{id}\" type=\"hidden\" />\n");
            html.Append($"      <span class=\"btn green fileinput-button\">\n");
            html.Append($"          <span>{btnText}</span>\n");
            html.Append($"          <input type=\"file\" id=\"fileupload_{id}\" name=\"uploadFile\" multiple=\"\">\n");
            html.Append($"      </span>\n");
            html.Append($"      <span class=\"help-inline\" id=\"span_{id}\"></span>\n");
            html.Append("   </div>\n");
            html.Append("</div>\n");
            
            return new HtmlString(html.ToString());
        }
        #region UploadFileJs
        /// <summary>
        /// 上传图片js
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="id">控件id</param>
        /// <returns></returns>
        public static IHtmlContent UploadFileJs(this IHtmlHelper htmlHelper, string id)
        {
            StringBuilder html = new StringBuilder();
            html.Append("$('#fileupload_" + id + "').fileupload({");
            html.Append("   disableImageResize: false,\n");
            html.Append("   autoUpload: true,\n");
            html.Append($"   url: '/Upload/UpdateFile?filePath={DateTime.Now.ToString("yyyyMM")}',\n");
            html.Append("   done: function (e, data) {\n");
            html.Append("       if (data.result.IsSuccess) {\n");

            html.Append($"          $(\"#span_{id}\").text(data.result.Data.FileName);\n");
            html.Append($"          $(\"#{id}\").val(data.result.Data.FileUrl);\n");
            html.Append("       } else {\n");
            html.Append("           alert(\"上传文件失败\");\n");
            html.Append("   }\n");
            html.Append("}\n");
            html.Append("});");
            return new HtmlString(html.ToString());
        }
        #endregion
        #endregion

        #region TextAreaFor 多行文本框
        /// <summary>
        /// 多行文本框
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="title">标题</param>
        /// <param name="id">控件id</param>
        /// <param name="rows">高</param>
        /// <param name="name">控件name(为空时，name=id)</param>
        /// <param name="classStr">class名称（默认有form-control，多个用空格隔开）</param>
        /// <param name="htmlAttributes">控件属性(格式:key='value')，多个用空格隔开</param>
        /// <param name="required">是否可空</param>
        /// <param name="titleWidth">title宽度(默认3)</param>
        /// <param name="inputWidth">文本框宽度(默认4)</param>
        /// <param name="value">默认值</param>
        /// <param name="isReadonly">文本框是否只读，true添加readonly='readonly'属性</param>
        /// <returns></returns>
        public static IHtmlContent TextAreaFor(this IHtmlHelper htmlHelper, string title, string id, int rows, string name = "", string classStr = "",
            string htmlAttributes = null, bool required = true, int titleWidth = 3, int inputWidth = 4, string value = "", bool isReadonly = false)
        {
            StringBuilder html = new StringBuilder();

            if (string.IsNullOrWhiteSpace(name)) name = id;
            if (isReadonly == true) htmlAttributes += " readonly=\"readonly\"";

            html.Append("<div class=\"form-group\">\n");
            html.Append($"   <label class=\"control-label col-xs-{titleWidth}\">{title}\n");
            if (required == true)
            {
                html.Append("       <span class=\"required\">*</span>\n");
            }
            html.Append("   </label>\n");
            html.Append($"   <div class=\"col-xs-{inputWidth}\">\n");
            html.Append($"      <textarea id=\"{id}\" name=\"{name}\" rows=\"{rows}\" class=\"form-control {classStr}\" {htmlAttributes}>{value}</textarea>\n");
            html.Append("   </div>\n");
            html.Append("</div>\n");
            return new HtmlString(html.ToString());
        }
        #endregion
        
    }
}
